package cz.muni.fi.pa165.musiclibrary.impl.service.auth;

import java.io.IOException;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.slf4j.LoggerFactory;

import cz.muni.fi.pa165.musiclibrary.api.service.auth.AuthException;
import cz.muni.fi.pa165.musiclibrary.api.service.auth.IAuthService;
import cz.muni.fi.pa165.musiclibrary.api.service.auth.IUser;

/**
 *
 * @author Maros Kucbel
 * @date 2013-01-22T17:52:29+0100
 */
public final class AuthService implements IAuthService {
    
    private Set<String> users = new HashSet<String>();
    
    @Override
    public IUser login(String userName, String password) {
        Validate.isTrue(StringUtils.isNotBlank(userName), "User name should not be null or blank.");
        Validate.isTrue(StringUtils.isNotBlank(password), "User password should not be null or blank.");
        
        Properties usersDB = new Properties();
        try {
            usersDB.load(AuthService.class.getResourceAsStream("users.properties"));
        } catch (IOException ex) {
            LoggerFactory.getLogger(AuthService.class).error("Cannot load user database.", ex);
        }
        String userPassword = usersDB.getProperty(userName);
        boolean authorized = password.equals(userPassword);
        if (authorized) {
            final User user = new User(userName, password);
            this.users.add(userName);
            return user;
        } else {
            throw new AuthException("Name and password don't match.");
        }
    }
    
    @Override
    public void logout(String userName) {
        this.users.remove(userName);
    }

    @Override
    public boolean isAuthorized(String userName) throws AuthException {
        if (userName == null) {
            return false;
        }
        return this.users.contains(userName);
    }
    
}